<template>
	<view class="container">
		<view class="back-to-top" v-show="showBackTop" @click="scrollToTop">
			<text class="yticon icon-fanhuidingbu"></text>
		</view>
		<view class="carousel">
			<swiper indicator-dots circular=true duration="500" interval="2000" autoplay="true">
				<swiper-item class="swiper-item" v-for="(item,index) in imgList" :key="index">
					<view class="image-wrapper">
						<image :src="item.src" class="loaded" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!--  秒杀 -->
		<view v-if="isMiao" class="miaoShaDi" @click="share">
			<view class="seckill-tag">
				<text class="tag-text">好物</text>
				<text class="tag-text">秒杀</text>
			</view>
			<text class="tit">
				<text class="tag-price">¥ {{goodsDetail.retailPrice}}</text>
				<text class="tag-price" style="font-size: 12px; text-decoration: line-through; margin-top: 5px;">¥{{goodsDetail.counterPrice}}</text>
				<!-- <text style="text-decoration: line-through; color: #fff;">
					¥{{goodsDetail.counterPrice}}
				</text> -->
			</text>
			<view class="countdown-container">
				<text class="countdown-tip">{{countdownText}}</text>
				<view class="timer-box">
					<span class="timer-item">{{countdownTime.split(':')[0]}}</span>
					<span class="colon">:</span>
					<span class="timer-item">{{countdownTime.split(':')[1]}}</span>
					<span class="colon">:</span>
					<span class="timer-item">{{countdownTime.split(':')[2]}}</span>
				</view>
			</view>
		</view>

		<view class="introduce-section">
			<text class="title">{{goodsDetail.name}}</text>
			<view class="price-box">
				<text class="price-tip">¥</text>
				<text class="price">{{goodsDetail.retailPrice}}</text>
				<text class="m-price">¥{{goodsDetail.counterPrice}}</text>
				<!-- <text class="coupon-tip">7折</text> -->
			</view>
			<view class="bot-row">
				<text>销量: {{goodsDetail.sales}}</text>
				<text>库存: {{goodsStock}}</text>
				<text>浏览量: {{goodsDetail.browse}}</text>
			</view>
		</view>

		<!--  分享 -->
		<!-- <view class="share-section" @click="share">
			<view class="share-icon">
				<text class="yticon icon-xingxing"></text>
				 返
			</view>
			<text class="tit">该商品分享可领49减10红包</text>
			<text class="yticon icon-bangzhu1"></text>
			<view class="share-btn">
				立即分享
				<text class="yticon icon-you"></text>
			</view>
		</view> -->

		<view class="c-list">
			<view class="c-row b-b" @click="toggleSpec">
				<text class="tit">购买类型</text>
				<view class="con">
					<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
						{{sItem.specifications}}
					</text>
				</view>
				<text class="yticon icon-you"></text>
			</view>
			<!-- <view class="c-row b-b">
				<text class="tit">优惠券</text>
				<text class="con t-r red">领取优惠券</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="c-row b-b">
				<text class="tit">促销活动</text>
				<view class="con-list">
					<text>新人首单送20元无门槛代金券</text>
					<text>订单满50减10</text>
					<text>订单满100减30</text>
					<text>单笔购买满两件免邮费</text>
				</view>
			</view> -->
			<view class="c-row b-b">
				<text class="tit">服务</text>
				<view class="bz-list con">
					<text>7天无理由退换货 ·</text>
					<text>假一赔十 ·</text>
				</view>
			</view>
		</view>

		<view class="container1">
			<view class="title1">商品参数</view>

			<view class="param-row1" v-for="(item,index) in goodsAttribute" :key="index">
				<view class="param-name1">{{item.attribute}}</view>
				<view class="param-value1">{{item.value}}</view>
			</view>
		</view>

		<!-- 评价 -->
		<view class="eva-section">
			<view class="e-header">
				<text class="tit">评价</text>
				<text>({{goodsComment.length}})</text>
				<text class="tip" @click="navToDetailPage1(goodsId)">更多评论</text>
				<text class="yticon icon-you"></text>
			</view>
			<view class="eva-box" v-for="(item,index) in goodsComment.slice(0, 2)" :key="index">
				<image class="portrait" :src="item.dtsUser.avatar" mode="aspectFill"></image>
				<view class="right">
					<text class="name">{{item.dtsUser.nickname}}</text>
					<text class="con">{{item.content}}</text>
					<view class="bot">
						<text class="attr"></text>
						<text class="time">{{item.addTime.slice(0,10)}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="detail-desc">
			<view class="d-header">
				<text>图文详情</text>
			</view>
			<!-- <rich-text :nodes="desc"></rich-text> -->
			<view class="uni-flex uni-column" style="width: 100%;">
				<view class="flex-item flex-item-V uni-bg-red" v-for="(item,index) in imgList" :key="index">
					<image :src="item.src" class="loaded" mode="aspectFill"></image>
				</view>
			</view>
		</view>


		<view class="detail-desc">
			<view class="d-header">
				<text>常见问题</text>
			</view>
			<view class="faq-item" v-for="(item,index) in issue" :key="index">
				<view class="faq-question"> · {{item.question}}</view>
				<view class="faq-answer">{{item.answer}}</view>
			</view>
		</view>

		<view class="detail-desc">
			<view class="d-header">
				<text>大家都在看</text>
			</view>
			<view class="guess-section">
				<view v-for="(item, index) in goodsList" :key="index" class="guess-item" @click="navToDetailPage(item)">
					<view class="image-wrapper">
						<image :src="item.picUrl" mode="aspectFill"></image>
					</view>
					<text class="title clamp">{{item.brief}}</text>
					<text class="price">￥{{item.counterPrice}}</text>
				</view>
			</view>
		</view>



		<!-- 底部操作菜单 -->
		<view class="page-bottom">
			<navigator url="/pages/index/index" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-xiatubiao--copy"></text>
				<text>首页</text>
			</navigator>
			<navigator url="/pages/cart/cart" open-type="switchTab" class="p-b-btn">
				<text class="yticon icon-gouwuche"></text>
				<text>购物车</text>
			</navigator>
			<view class="p-b-btn" :class="{active: favorite}" @click="toFavorite">
				<text class="yticon icon-shoucang"></text>
				<text>收藏</text>
			</view>

			<view class="action-btn-group"  :class="{ 'no-split-line': isMiao }">
				<button type="primary" v-if="isMiao && isMai" class=" action-btn no-border buy-now-btn" @click="buy">立即购买</button>
				<button type="primary" v-if="isMiao && !isMai" disabled class=" action-btn no-border buy-now-btn" @click="buy">立即购买</button>
				<button type="primary" v-if="!isMiao" class=" action-btn no-border buy-now-btn" @click="buy">立即购买</button>
				<button type="primary" v-if="!isMiao" class=" action-btn no-border add-cart-btn"
					@click="addCart">加入购物车</button>
			</view>
		</view>


		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<view class="a-t">
					<image :src="specSelected[0].url"></image>
					<view class="right">
						<text class="price">¥{{specSelected[0].price}}</text>
						<text class="stock">库存：{{specSelected[0].number}}件</text>
						<view class="selected">
							已选：
							<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
								{{sItem.specifications}}
							</text>
						</view>
					</view>
				</view>
				<!-- 颜色/尺寸 -->
				<!-- <view v-for="(item,index) in goodsSpecification" :key="index" class="attr-list">
					<text>{{item.specification}}</text>
					<view class="item-list">
						<text 
							v-for="(childItem, childIndex) in item.goodsSpecificationList" 
							:key="childIndex" class="tit"
							:class="{selected: childIndex==0}"
							@click="selectSpec(index,childIndex,childItem.id)"
						>
						 @click="selectSpec(index,childIndex,childItem.id)" 
							{{childItem.value}}
						</text>
					</view>
				</view>
				<button class="btn" @click="toggleSpec">完成</button> -->


				<view class="attr-list">
					<text>规格</text>
					<view class="item-list">
						<text class="tit" v-for="(item,index) in goodsSpecification" :key="index"
							:class="{selected: item.selected}" @click="selectSpec1(index,item.id)">
							<!-- @click="selectSpec(index,childIndex,childItem.id)" -->
							{{item.specifications}}
						</text>
					</view>
				</view>
				<view class="quantity-selector">
					<view class="quantity-btn minus" @click="decreaseQuantity"> - </view>
					<input type="number" :value="num" :min="1" :max="specSelected[0].number" class="quantity-input"
						@input="onQuantityInput" @blur="handleInputQuantity">
					<view class="quantity-btn plus" @click="increaseQuantity"> + </view>
				</view>
				<button class="btn" @click="toggleSpec">完成</button>
			</view>
		</view>
		<!-- 分享 -->
		<share ref="share" :contentHeight="580" :shareList="shareList"></share>
	</view>
</template>

<script>
	import share from '@/components/share';
	import {
		getGoodsDetail,
		getGoodsAttribute
	} from '@/config/api/goods.js';
	import {
		getIssue,
		getSeeBoth,
		getGoodsSpecification,
		getGoodsProduct,
		getSeckillProduct,
		getBrandById,
		insFootprint,
		getComment,
		getGoodsStock
	} from '@/config/api/goodsDetail.js';
	import {
		getUserCollect,
		insUserCollect,
		delUserCollect
	} from '@/config/api/user.js';
	import {
		addCart
	} from '@/config/api/cart.js';
	import {
		mapState
	} from 'vuex';
	export default {
		components: {
			share
		},
		computed: {
			...mapState(['hasLogin', 'userInfo'])
		},
		data() {
			return {
				startTime: '10:00', // 示例开始时间
				endTime: '11:00',   // 示例结束时间
				timer: null,        // 计时器
				countdownText: '',  // 倒计时显示文本
				countdownTime: '',  // 倒计时时间
				showBackTop: false,
				isMiao: false, // 判断是否是秒杀
				isMai: false,
				goodsId: 0,
				specClass: 'none',
				specSelected: [],
				brand: {},
				// 大家都在看
				goodsList: [],
				// 商品信息
				goodsDetail: {},
				// 商品选择规格的商品价格
				goodsSpecificationPrice: 0,
				// 常见问题
				issue: [],
				brand: {},
				// 商品属性
				goodsAttribute: [],
				// 商品评论
				goodsComment: [],
				favorite: true,
				shareList: [],
				imgList: [{
						src: 'https://gd3.alicdn.com/imgextra/i3/0/O1CN01IiyFQI1UGShoFKt1O_!!0-item_pic.jpg_400x400.jpg'
					},
					{
						src: 'https://gd3.alicdn.com/imgextra/i3/TB1RPFPPFXXXXcNXpXXXXXXXXXX_!!0-item_pic.jpg_400x400.jpg'
					},
					{
						src: 'https://gd2.alicdn.com/imgextra/i2/38832490/O1CN01IYq7gu1UGShvbEFnd_!!38832490.jpg_400x400.jpg'
					}
				],
				desc: `
					<div style="width:100%">
						<img style="width:100%;display:block;" src="https://gd3.alicdn.com/imgextra/i4/479184430/O1CN01nCpuLc1iaz4bcSN17_!!479184430.jpg_400x400.jpg" />
						<img style="width:100%;display:block;" src="https://gd2.alicdn.com/imgextra/i2/479184430/O1CN01gwbN931iaz4TzqzmG_!!479184430.jpg_400x400.jpg" />
						<img style="width:100%;display:block;" src="https://gd3.alicdn.com/imgextra/i3/479184430/O1CN018wVjQh1iaz4aupv1A_!!479184430.jpg_400x400.jpg" />
						<img style="width:100%;display:block;" src="https://gd4.alicdn.com/imgextra/i4/479184430/O1CN01tWg4Us1iaz4auqelt_!!479184430.jpg_400x400.jpg" />
						<img style="width:100%;display:block;" src="https://gd1.alicdn.com/imgextra/i1/479184430/O1CN01Tnm1rU1iaz4aVKcwP_!!479184430.jpg_400x400.jpg" />
					</div>
				`,
				goodsSpecification: [],
				num: 1,
				goodsStock: 0, // 商品库存
			};
		},
		async onLoad(options) {
			// 接收传值,id
			let id;
			let seckillBatch;
			// 先检查 dtsGoods.id 是否存在
			console.log(JSON.stringify(options, null, 2));
			if (options.goodsId) {
				id = options.goodsId;
				seckillBatch = options.seckillBatch;
				this.startTime = options.seckillBatch;
				this.endTime = options.endTime;
				this.isMiao = true;
				// 初始化倒计时
				this.initCountdown();
			}
			// 再检查普通 id 是否存在
			else if (options.id) {
				id = options.id;
			}
			// 如果都不存在，处理错误情况
			else {
				console.error('未接收到商品ID');
				// 可以显示错误提示或执行其他逻辑
				return;
			}

			this.goodsId = id;

			try { // 商品详情
				const res = await getGoodsDetail({
					id
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
					this.goodsDetail = res.data.data
					// console.log("xiangqing" + this.goodsDetail);
					console.log(JSON.stringify(this.goodsDetail, null, 2));
					let trimmedGallery = this.goodsDetail.gallery.slice(1, -1);
					// 按逗号分割成数组，同时去除字符串两边可能残留的双引号
					let linkArray = trimmedGallery.split(',').map(link => link.replace(/^"|"$/g, ''));
					// 转换为目标格式的数组对象
					this.imgList = linkArray.map((src) => {
						return {
							src: src
						};
					});

				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			try {
				const userId = this.userInfo.id;
				const res = await insFootprint({
					goodsId: id,
					userId
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {

				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			// 商品总库存
			try {
				const res = await getGoodsStock({
					goodsId: id
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
					this.goodsStock = res.data.data;
				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			try { // 商品属性
				const res = await getGoodsAttribute({
					id
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
					this.goodsAttribute = res.data.data
					// console.log("商品属性" + this.goodsAttribute);
				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			try { // 商品评论
				const res = await getComment({
					id
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
					this.goodsComment = res.data.data
					// console.log("商品评论" + this.goodsComment);
					// console.log(JSON.stringify(this.goodsComment[0], null, 2));
				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			try { // 用户是否收藏
				let valueId = id
				let userId = this.userInfo.id;
				let type = 0
				const res = await getUserCollect({
					valueId,
					userId,
					type
				})
				if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
					console.log(JSON.stringify(res.data.data[0], null, 2));
					if (res.data.data[0] != undefined) {
						this.favorite = res.data.data[0].id == id;
						console.log("是否收藏" + this.favorite);
						console.log("aslkjfklasjdklfjaksldjfasjdfl");
					} else {
						this.favorite = false;
						console.log("是否收藏" + this.favorite);
					}

				} else {
					console.error('请求失败:', res?.data?.msg || '未知错误');
				}
			} catch (error) {
				console.error('接口异常:', error)
				this.$message.error('数据加载失败')
			}

			if (!this.isMiao) {
				try { // 商品规格
					const res = await getGoodsProduct({
						goodsId: id
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.goodsSpecification = res.data.data
						this.goodsSpecification[0].selected = true;
						this.specSelected.push(this.goodsSpecification[0]);
						// console.log("商品规格" + this.goodsSpecification);
						console.log(JSON.stringify(this.goodsSpecification, null, 2));
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			} else if (this.isMiao) {
				try { // 秒杀商品规格
					const res = await getSeckillProduct({
						goodsId: id,
						seckillBatch: seckillBatch
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.goodsSpecification = res.data.data
						this.goodsSpecification[0].selected = true;
						this.goodsSpecification.forEach(item => {
							item.price = item.dtsSeckillBatch.flashSalePrice;
						})
						this.specSelected.push(this.goodsSpecification[0]);
						this.goodsDetail.counterPrice = this.goodsDetail.retailPrice;
						this.goodsDetail.retailPrice = this.specSelected[0].price;
						// console.log("商品规格" + this.goodsSpecification);
						console.log(JSON.stringify(this.goodsSpecification, null, 2));
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			}




			this.loadData();

			//规格 默认选中第一条
			// this.specList.forEach(item=>{
			// 	for(let cItem of this.specChildList){
			// 		if(cItem.pid === item.id){
			// 			this.$set(cItem, 'selected', true);
			// 			this.specSelected.push(cItem);
			// 			break; //forEach不能使用break
			// 		}
			// 	}
			// })
			this.shareList = await this.$api.json('shareList');
		},
		onPageScroll(e) {
			this.showBackTop = e.scrollTop >= 1000; // 滚动超过500px显示按钮
		},
		methods: {
			async loadData() {
				try { // 广告
					const res = await getIssue()
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.issue = res.data.data
						// this.swiperLength = this.carouselList.length;
						// console.log(this.carouselList);
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
				let categoryId = this.goodsDetail.categoryId;

				try { // 大家都在看
					const res = await getSeeBoth({
						categoryId
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.goodsList = res.data.data
						console.log(this.goodsList);
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			//规格弹窗开关
			toggleSpec() {
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
				}
			},
			//选择规格
			// selectSpec(index,childIdx, id){
			// //index=>父级
			// if(index==0){
			// 	let parentItem = this.goodsSpecification[0]; //米色
			// 	parentItem[childIdx].selected=true;
			// 	//遍历中间表中实际可用的子选项==》//规格和商品的库存，单价配置==》米色和规格可用
			// 	//子级重新渲染==》遍历=》将不满足条件的disabled属性设置为true
			// }else{
			// 	 this.goodsSpecification[1][childIdx].selected=true;
			// 	//子级重新渲染==》遍历=》将所有的选中设置为false;
			// 	//childIdx=》选中=》true
			// }
			// //childIdx=>子级
			// //id=》选中的项

			// let list = this.specChildList;
			// list.forEach(item=>{
			// 	if(item.id === id){
			// 		this.$set(item, 'selected', false);
			// 	}
			// })
			// this.$set(list[index], 'selected', true);
			// //存储已选择
			// /**
			//  * 修复选择规格存储错误
			//  * 将这几行代码替换即可
			//  * 选择的规格存放在specSelected中
			//  */
			// this.specSelected = []; 
			// list.forEach(item=>{ 
			// 	if(item.selected === true){ 
			// 		this.specSelected.push(item); 
			// 	} 
			// })

			// },
			selectSpec1(index, id) {
				let list = this.goodsSpecification;
				list.forEach(item => {
					this.$set(item, 'selected', false);
				})
				this.$set(list[index], 'selected', true);
				this.specSelected = [];
				list.forEach(item => {
					if (item.selected === true) {
						this.specSelected.push(item);
					}
				});
				this.num = 1;
				console.log(this.num);
			},
			//分享
			share() {
				this.$refs.share.toggleMask();
			},
			//收藏
			async toFavorite() {
				if (!this.hasLogin) {
					uni.navigateTo({
						url: '/pages/public/login'
					});
					return; // 终止后续执行
				}

				let userId = this.userInfo.id;
				let valueId = this.goodsDetail.id;
				let type = 0;
				if (this.favorite) {
					try { // 取消收藏
						const res = await delUserCollect({
							userId,
							valueId,
							type
						})
						if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
							200) {
							// this.issue = res.data.data
							// this.swiperLength = this.carouselList.length;
							// console.log(this.carouselList);
							uni.showToast({
								title: '已取消收藏',
								icon: 'none',
								duration: 2000
							});
						} else {
							console.error('请求失败:', res?.data?.msg || '未知错误');
						}
					} catch (error) {
						console.error('接口异常:', error)
						this.$message.error('数据加载失败')
					}
					this.favorite = !this.favorite;
				} else {
					try { // 收藏
						const res = await insUserCollect({
							userId,
							valueId,
							type
						})
						if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
							200) {
							// this.issue = res.data.data
							// this.swiperLength = this.carouselList.length;
							// console.log(this.carouselList);
							uni.showToast({
								title: '收藏成功',
								icon: 'none',
								duration: 2000
							});
						} else {
							console.error('请求失败:', res?.data?.msg || '未知错误');
						}
					} catch (error) {
						console.error('接口异常:', error)
						this.$message.error('数据加载失败')
					}
					this.favorite = !this.favorite;
				}

			},
			async buy() {

				if (!this.hasLogin) {
					uni.navigateTo({
						url: '/pages/public/login'
					});
					return; // 终止后续执行
				}

				await this.selBrand(this.goodsDetail.brandId);
				let brandName = this.brand.name;
				// let dtsCart = {
				// 	userId: 1,
				// 	brandId: this.goodsDetail.brandId,
				// 	brandName: brandName,
				// 	goodsId: this.goodsDetail.id,
				// 	goodsSn: this.goodsDetail.goodsSn,
				// 	goodsName: this.goodsDetail.name,
				// 	productId: this.specSelected[0].id,
				// 	price: this.specSelected[0].price,
				// 	number: this.num,
				// 	specifications: this.specSelected[0].specifications,
				// 	checked: 1,
				// 	picUrl: this.specSelected[0].url,
				// }

				let brandGroups = [{
					name: brandName,
					goods: [{
						userId: this.userInfo.id,
						goodsId: this.goodsDetail.id,
						goodsName: this.goodsDetail.name,
						price: this.specSelected[0].price,
						number: this.num,
						picUrl: this.specSelected[0].url,
						productId: this.specSelected[0].id,
						categoryId : this.goodsDetail.categoryId,
						specifications: this.specSelected[0].specifications,
						goodsSn: this.goodsDetail.goodsSn,
						brandId: this.goodsDetail.brandId,
					}],
				}]



				uni.navigateTo({
					url: `/pages/order/createOrder?data=${encodeURIComponent(JSON.stringify({
						brands: brandGroups,  // 使用分层结构
						total: this.specSelected[0].price,
						isMiao: this.isMiao,
						isMai: this.isMai
					}))}`
				});
			},
			async selBrand(id) {
				try {
					const res = await getBrandById({
						id: id
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.brand = res.data.data;
						console.log("品牌" + this.brand.name);
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			stopPrevent() {},
			//详情页
			navToDetailPage(item) {
				//测试数据没有写id，用title代替
				let id = item.id;
				uni.navigateTo({
					url: `/pages/product/product?id=${id}`
				})
			},

			navToDetailPage1(item) {
				let id = item;
				uni.navigateTo({
					url: `/pages/detail/detailComment?id=${id}`
				})
			},
			onQuantityInput(e) {
				// 实时显示输入（不验证）
				this.num = e.target.value;
			},
			handleInputQuantity(e) {
				let inputValue = Number(e.target.value);
				const stock = this.specSelected[0].number;
				this.num = Math.max(1, Math.min(inputValue, stock)); // 确保1 ≤ num ≤ stock
			},
			increaseQuantity() {
				if (this.num < this.specSelected[0].number) this.num++;
			},
			decreaseQuantity() {
				if (this.num > 1) this.num--;
			},
			async addCart() {
				if (!this.hasLogin) {
					uni.navigateTo({
						url: '/pages/public/login'
					});
					return; // 终止后续执行
				}
				console.log(this.goodsDetail);
				let dtsCart = {
					userId: this.userInfo.id,
					brandId: this.goodsDetail.brandId,
					goodsId: this.goodsDetail.id,
					goodsSn: this.goodsDetail.goodsSn,
					goodsName: encodeURIComponent(this.goodsDetail.name),
					productId: this.specSelected[0].id,
					price: this.specSelected[0].price,
					number: this.num,
					specifications: encodeURIComponent(this.specSelected[0].specifications),
					checked: 1,
					picUrl: encodeURIComponent(this.specSelected[0].url),
				}
				try { // 加入购物车
					console.log(this.goodsDetail);
					const res = await addCart(dtsCart)
					console.log(JSON.stringify(res, null, 2));
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						uni.showToast({
							title: '加入成功',
							icon: 'none',
							duration: 2000
						});
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},
			// 滚动到顶部
			scrollToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300 // 滚动动画时长（毫秒）
				});
			},
			// 初始化倒计时
			  initCountdown() {
			    this.updateCountdown();
			    // 每秒更新一次倒计时
			    this.timer = setInterval(() => {
			      this.updateCountdown();
			    }, 1000);
			  },
			  
			  // 更新倒计时显示
			  updateCountdown() {
			    const now = new Date();
			    const currentHours = now.getHours();
			    const currentMinutes = now.getMinutes();
			    const currentSeconds = now.getSeconds();
			    
			    // 将开始和结束时间转换为小时和分钟
			    const [startHours, startMinutes] = this.startTime.split(':').map(Number);
			    const [endHours, endMinutes] = this.endTime.split(':').map(Number);
			    
			    // 计算当前时间、开始时间和结束时间的总秒数
			    const currentTimeInSeconds = currentHours * 3600 + currentMinutes * 60 + currentSeconds;
			    const startTimeInSeconds = startHours * 3600 + startMinutes * 60;
			    const endTimeInSeconds = endHours * 3600 + endMinutes * 60;
			    
			    let diffSeconds;
			    
			    if (currentTimeInSeconds < startTimeInSeconds) {
			      // 还未开始，计算距离开始的时间
			      this.countdownText = '距离开始还剩';
			      diffSeconds = startTimeInSeconds - currentTimeInSeconds;
				  this.isMai = false;
			    } else if (currentTimeInSeconds < endTimeInSeconds) {
			      // 正在进行中，计算距离结束的时间
			      this.countdownText = '距离结束还剩';
			      diffSeconds = endTimeInSeconds - currentTimeInSeconds;
				  this.isMai = true;
			    } else {
			      // 已结束，重置倒计时
			      this.countdownText = '今日秒杀已结束';
			      this.countdownTime = '00:00:00';
			      clearInterval(this.timer);
			      this.timer = null;
				  this.isMai = false;
			      return;
			    }
			    
			    // 计算剩余的时、分、秒
			    const hours = Math.floor(diffSeconds / 3600);
			    const minutes = Math.floor((diffSeconds % 3600) / 60);
			    const seconds = diffSeconds % 60;
			    
			    // 格式化显示
			    this.countdownTime = `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
			  },
			  
			  // 数字补零
			  padZero(num) {
			    return num < 10 ? `0${num}` : num;
			  },
			  
			  // 页面卸载时清除计时器
			  onUnload() {
			    if (this.timer) {
			      clearInterval(this.timer);
			      this.timer = null;
			    }
			  },
		},

	}
</script>

<style lang='scss'>
	page {
		background: $page-color-base;
		padding-bottom: 160upx;
	}

	.icon-you {
		font-size: $font-base + 2upx;
		color: #888;
	}

	.carousel {
		height: 722upx;
		position: relative;

		swiper {
			height: 100%;
		}

		.image-wrapper {
			width: 100%;
			height: 100%;
		}

		.swiper-item {
			display: flex;
			justify-content: center;
			align-content: center;
			height: 750upx;

			image {
				width: 100%;
				height: 100%;
			}
		}

	}

	/* 标题简介 */
	.introduce-section {
		background: #fff;
		padding: 20upx 30upx;

		.title {
			font-size: 32upx;
			color: $font-color-dark;
			height: 50upx;
			line-height: 50upx;
		}

		.price-box {
			display: flex;
			align-items: baseline;
			height: 64upx;
			padding: 10upx 0;
			font-size: 26upx;
			color: $uni-color-primary;
		}

		.price {
			font-size: $font-lg + 2upx;
		}

		.m-price {
			margin: 0 12upx;
			color: $font-color-light;
			text-decoration: line-through;
		}

		.coupon-tip {
			align-items: center;
			padding: 4upx 10upx;
			background: $uni-color-primary;
			font-size: $font-sm;
			color: #fff;
			border-radius: 6upx;
			line-height: 1;
			transform: translateY(-4upx);
		}

		.bot-row {
			display: flex;
			align-items: center;
			height: 50upx;
			font-size: $font-sm;
			color: $font-color-light;

			text {
				flex: 1;
			}
		}
	}

	/* 分享 */
	.share-section {
		display: flex;
		align-items: center;
		color: $font-color-base;
		background: linear-gradient(left, #fdf5f6, #fbebf6);
		padding: 12upx 30upx;

		.share-icon {
			display: flex;
			align-items: center;
			width: 70upx;
			height: 30upx;
			line-height: 1;
			border: 1px solid $uni-color-primary;
			border-radius: 4upx;
			position: relative;

			font-size: 22upx;
			color: $uni-color-primary;

			&:after {
				content: '';
				width: 50upx;
				height: 50upx;
				border-radius: 50%;
				left: -20upx;
				top: -12upx;
				position: absolute;
				background: $uni-color-primary;
			}
		}

		.icon-xingxing {
			position: relative;
			z-index: 1;
			font-size: 24upx;
			margin-left: 2upx;
			margin-right: 10upx;
			color: #fff;
			line-height: 1;
		}

		.tit {
			font-size: $font-base;
			margin-left: 10upx;
		}

		.icon-bangzhu1 {
			padding: 10upx;
			font-size: 30upx;
			line-height: 1;
		}

		.share-btn {
			flex: 1;
			text-align: right;
			font-size: $font-sm;
			color: $uni-color-primary;
		}

		.icon-you {
			font-size: $font-sm;
			margin-left: 4upx;
			color: $uni-color-primary;
		}
	}

	.c-list {
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		background: #fff;

		.c-row {
			display: flex;
			align-items: center;
			padding: 20upx 30upx;
			position: relative;
		}

		.tit {
			width: 140upx;
		}

		.con {
			flex: 1;
			color: $font-color-dark;

			.selected-text {
				margin-right: 10upx;
			}
		}

		.bz-list {
			height: 40upx;
			font-size: $font-sm+2upx;
			color: $font-color-dark;

			text {
				display: inline-block;
				margin-right: 30upx;
			}
		}

		.con-list {
			flex: 1;
			display: flex;
			flex-direction: column;
			color: $font-color-dark;
			line-height: 40upx;
		}

		.red {
			color: $uni-color-primary;
		}
	}

	/* 评价 */
	.eva-section {
		display: flex;
		flex-direction: column;
		padding: 20upx 30upx;
		background: #fff;
		margin-top: 16upx;

		.e-header {
			display: flex;
			align-items: center;
			height: 70upx;
			font-size: $font-sm + 2upx;
			color: $font-color-light;

			.tit {
				font-size: $font-base + 2upx;
				color: $font-color-dark;
				margin-right: 4upx;
			}

			.tip {
				flex: 1;
				text-align: right;
			}

			.icon-you {
				margin-left: 10upx;
			}
		}
	}

	.eva-box {
		display: flex;
		padding: 20upx 0;

		.portrait {
			flex-shrink: 0;
			width: 80upx;
			height: 80upx;
			border-radius: 100px;
		}

		.right {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-base;
			color: $font-color-base;
			padding-left: 26upx;

			.con {
				font-size: $font-base;
				color: $font-color-dark;
				padding: 20upx 0;
			}

			.bot {
				display: flex;
				justify-content: space-between;
				font-size: $font-sm;
				color: $font-color-light;
			}
		}
	}

	/*  详情 */
	.detail-desc {
		background: #fff;
		margin-top: 16upx;

		.d-header {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 80upx;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			position: relative;

			text {
				padding: 0 20upx;
				background: #fff;
				position: relative;
				z-index: 1;
			}

			&:after {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translateX(-50%);
				width: 300upx;
				height: 0;
				content: '';
				border-bottom: 1px solid #ccc;
			}
		}
	}

	/* 规格选择弹窗 */
	.attr-content {
		padding: 10upx 30upx;

		.a-t {
			display: flex;

			image {
				width: 170upx;
				height: 170upx;
				flex-shrink: 0;
				margin-top: -40upx;
				border-radius: 8upx;
				;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24upx;
				font-size: $font-sm + 2upx;
				color: $font-color-base;
				line-height: 42upx;

				.price {
					font-size: $font-lg;
					color: $uni-color-primary;
					margin-bottom: 10upx;
				}

				.selected-text {
					margin-right: 10upx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: $font-base + 2upx;
			color: $font-color-base;
			padding-top: 30upx;
			padding-left: 10upx;
		}

		.item-list {
			padding: 20upx 0 0;
			display: flex;
			flex-wrap: wrap;

			text {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-right: 20upx;
				margin-bottom: 20upx;
				border-radius: 100upx;
				min-width: 60upx;
				height: 60upx;
				padding: 0 20upx;
				font-size: $font-base;
				color: $font-color-dark;
			}

			.selected {
				background: #fbebee;
				color: $uni-color-primary;
			}
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 40vh;
			border-radius: 10upx 10upx 0 0;
			background-color: #fff;

			.btn {
				height: 66upx;
				line-height: 66upx;
				border-radius: 100upx;
				background: $uni-color-primary;
				font-size: $font-base + 2upx;
				color: #fff;
				margin: 30upx auto 20upx;
			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}

	/* 底部操作菜单 */
	.page-bottom {
		position: fixed;
		left: 30upx;
		bottom: 30upx;
		z-index: 95;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 690upx;
		height: 100upx;
		background: rgba(255, 255, 255, .9);
		box-shadow: 0 0 20upx 0 rgba(0, 0, 0, .5);
		border-radius: 16upx;

		.p-b-btn {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			font-size: $font-sm;
			color: $font-color-base;
			width: 96upx;
			height: 80upx;

			.yticon {
				font-size: 40upx;
				line-height: 48upx;
				color: $font-color-light;
			}

			&.active,
			&.active .yticon {
				color: $uni-color-primary;
			}

			.icon-fenxiang2 {
				font-size: 42upx;
				transform: translateY(-2upx);
			}

			.icon-shoucang {
				font-size: 46upx;
			}
		}

		.action-btn-group {
		  display: flex;
		  height: 76upx;
		  border-radius: 100px;
		  
		  // 合并两个 box-shadow 为一个
		  box-shadow: 0 20upx 40upx -16upx #fa436a, 1px 2px 5px rgba(219, 63, 96, 0.4);
		  
		  background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
		  margin-left: 20upx;
		  position: relative;
		
		  // 分割线默认显示
		  &:after {
		    content: '';
		    position: absolute;
		    top: 50%;
		    right: 50%;
		    transform: translateY(-50%);
		    height: 28upx;
		    width: 0;
		    border-right: 1px solid rgba(255, 255, 255, .5);
		  }
		
		  // 当添加 no-split-line 类时隐藏分割线
		  &.no-split-line:after {
		    display: none;
		  }
		
		  .action-btn {
		    display: flex;
		    align-items: center;
		    justify-content: center;
		    width: 180upx;
		    height: 100%;
		    font-size: $font-base;
		    padding: 0;
		    border-radius: 0;
		    background: transparent;
		  }
		}
	}

	.loaded {
		width: 100%;
	}

	.flex-item,
	.flex-item-V,
	.uni-bg-red {
		margin: 0;
		padding: 0;
	}

	.faq-container {
		padding: 20rpx;
		width: 90%;
		margin: 0 auto;
	}

	.faq-title {
		text-align: center;
		font-size: 32rpx;
		margin-bottom: 20rpx;
	}

	.faq-line {
		height: 2rpx;
		background-color: #ccc;
		margin-bottom: 20rpx;
	}

	.faq-item {
		margin-left: 10px;
		margin-bottom: 30rpx;
	}

	.faq-question {
		font-weight: bold;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.faq-answer {
		font-size: 26rpx;
		line-height: 1.6;
		color: #666;
	}

	.guess-section {
		display: flex;
		flex-wrap: wrap;
		padding: 0 30upx;
		background: #fff;

		.guess-item {
			display: flex;
			flex-direction: column;
			width: 48%;
			padding-bottom: 40upx;

			&:nth-child(2n+1) {
				margin-right: 4%;
			}
		}

		.image-wrapper {
			width: 100%;
			height: 330upx;
			border-radius: 3px;

			image {
				width: 100%;
				height: 100%;
				opacity: 1;
			}
		}

		.title {
			font-size: $font-lg;
			color: $font-color-dark;
			line-height: 80upx;
		}

		.price {
			font-size: $font-lg;
			color: $uni-color-primary;
			line-height: 1;
		}
	}

	.container1 {
		margin-top: 5px;
		margin-bottom: 5px;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;

	}

	.title1 {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		border-left: 6rpx solid #07C160;
		padding-left: 10rpx;
	}

	.param-row1 {
		display: flex;
		margin-bottom: 2rpx;
		font-size: 32rpx;
		background-color: #F7F7F7;
	}

	.param-name1 {
		margin-left: 15px;
		width: 200rpx;
		color: #666666;
		font-weight: 900;
		line-height: 40px;
	}

	.param-value1 {
		flex: 1;
		color: #333;
		line-height: 40px;
	}

	.footer1 {
		margin-top: 30rpx;
		text-align: right;
		font-size: 24rpx;
		color: #999;
	}

	.quantity-selector {
		display: flex;
		align-items: center;
		margin-top: 10upx;
	}

	.quantity-btn {
		background-color: #eee;
		width: 40upx;
		height: 40upx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30upx;
		cursor: pointer;
	}

	.quantity-input {
		width: 60upx;
		height: 40upx;
		text-align: center;
		border: 1px solid #ccc;
		margin: 0 10upx;
	}

	.miaoShaDi {
		display: flex;
		align-items: center;
		color: $font-color-base;
		background: linear-gradient(to right, #F42D8F, #FF0956);
		padding: 12upx 30upx;
		height: 50px;

		.share-btn {
			flex: 1;
			text-align: right;
			font-size: $font-sm;
			color: $uni-color-primary;
		}

		.seckill-tag {
			/* 按需定位，比如放在轮播图角落 */
			background-color: #CD156C;
			border-radius: 50px;
			/* 让内部元素垂直排列（也可用 flex 方案） */
			display: inline-block;
			padding: 10rpx 6rpx;
			padding-right: 5px;
			border-radius: 4rpx;
			/* 文字居中，可选 */
			text-align: center;
		}

		.tag-text {
			/* 关键：让每个文字块独占一行 */
			display: block;
			color: #fff;
			font-size: 30rpx;
			font-weight: 900;
			font-style: italic;
			/* 调整行高，让上下字间距合适 */
			line-height: 28rpx;
		}

		.tag-price {
			/* 关键：让每个文字块独占一行 */
			display: block;
			color: #fff;
			font-size: 30rpx;
			font-weight: 900;
			/* 调整行高，让上下字间距合适 */
			line-height: 28rpx;
			margin-left: 6px;
		}

		.countdown-container {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 4upx;
			margin-left: auto; // 新增：整体靠右
			padding-right: 10upx; // 新增：右侧内边距

			.countdown-tip {
				color: #fff;
				font-size: 24upx;
			}

			.timer-box {
				display: flex;
				align-items: center;
				gap: 4upx;
				background: rgba(0, 0, 0, 0.3);
				padding: 6upx 12upx;
				border-radius: 16upx;

				.timer-item,
				.colon {
					color: #fff;
					font-size: 26upx;
					font-weight: bold;
				}

				.colon {
					color: rgba(255, 255, 255, 0.7);
				}
			}
		}

	}



	/* 返回顶部按钮样式 */
	.back-to-top {
		position: fixed;
		right: 30upx;
		bottom: 320upx;
		z-index: 99;
		width: 60upx;
		height: 60upx;
		background: rgba(0, 0, 0, 0.8);
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;

		transition: all 0.3s ease;

		&.show {
			opacity: 1;
			visibility: visible;
		}

		.yticon {
			font-size: 36upx;
			color: #fff;
		}
	}

	/* 图标字体（需根据实际图标库调整） */
	.icon-fanhuidingbu::before {
		content: "\e601";
		/* 替换为实际图标 Unicode */
	}
</style>